#####################################################################
# Product:      KnowledgeEngine (Plone Edition)
#
# File:         PageList.py
#
# Copyright:    Copyright (c) 2004, Faulkner Technologies
#
# Author:       Brian Oliver
#
# Description:  This file defines the PageList toolbar tool, a simple
#               dropdown list to navigate through pages in an
#               asessment.
#
# See Also:     Element, Toolbar
#####################################################################

#####################################################################
## Knowledge Engine Library Imports
from Products.KnowledgeEngine.Common import *
from Products.KnowledgeEngine.Core import *
from Products.KnowledgeEngine.Elements.Toolbar.ToolbarTool import ToolbarTool, ToolbarToolInfo
from Products.KnowledgeEngine.PropertyDefinition import *
from Products.KnowledgeEngine.PropertyTypes import *
from Products.KnowledgeEngine.PropertyFormats import *
from Products.KnowledgeEngine.PropertyStructures import *

#####################################################################
## Zope Library Imports
from Globals import DTMLFile
from App.ImageFile import ImageFile

#####################################################################
## Python Library Imports
# (none)

#####################################################################
## PageListInfo Class Definition
class PageListInfo(ToolbarToolInfo):
    """
        Defines the class info methods, defining information about
        the class without needing an instance of the class
    """

    #---------------------------------------------------------------#

    def getClassName(self):
        """
            Returns the name of the class for which
            we are providing information.
        """
        return "PageList"

    #---------------------------------------------------------------#

    def getDisplayName(self):
        """
            Return a friendly name for the class instances
            (this is used for displaying in lists etc)
        """

        return "Page Navigation Dropdown"

    #---------------------------------------------------------------#

    def getIdentityType(self):
        """
            Return the identity type.
        """

        return "toolPageList"

    #---------------------------------------------------------------#

    def getClassIcon(self):
        """
            Return the appropriate icon file for the class.
        """

        return ImageFile('skins/PageList_icon.png', globals())

    #---------------------------------------------------------------#

    def isPermittedInContainer(self, containerClassInfo, containerInstance = None, instance=None):
        """
            ABSTRACT: Returns if class instances (instance) is permitted in
            the specified container (containerInstance)

            NOTE: This is from this class' instance perspective.
        """

        #DEFAULT RULE: PageLists are only permitted in Toolbars
        return containerClassInfo.isInstanceOf('Toolbar') and ((containerInstance == None) or (containerInstance != None and len(containerInstance.getChildrenByInstanceOf(self.getClassName())) == 0))

    #---------------------------------------------------------------#

    def onConfigureProperties(self):
        """
            Automatically called by the Knowledge Engine once
            the class has been loaded.  Use this method to register
            class specific properties using the PropertyReflection interface.

            If this class is sub-classed, a call must be made to
            the super-class to ensure super-class properties are
            correctly registered

            NOTE: This method is called before ClassInfo.onAfterStartup()
        """

        #initialise the super-class properties for reflection
        ToolbarToolInfo.onConfigureProperties(self)

        #set the default 'title'
        self.getPropertyDefinition('title').setDefaultValue('Pages')

        #set the default 'id'
        self.getPropertyDefinition('id').setDefaultValue('lstPages')

    #---------------------------------------------------------------#

#####################################################################
## PageList Class Definition
class PageList(ToolbarTool):
    """
        A class to represent a list of model sections in a model toolbar
    """

    #---------------------------------------------------------------#

    #ABSTRACT TRANSIENT: a ClassInfo implementation instance to provide info about this class
    _CLASSINFO = PageListInfo()

    #---------------------------------------------------------------#

    # Custom zope manage_preview to permit previews of components.
    preview_html = DTMLFile('index_html', globals())

    #---------------------------------------------------------------#

    def __init__(self, id, identity):
        "Constructor for the PageList"

        ToolbarTool.__init__(self, id, identity)

        #perform onAfterInstanciation processing
        self.onAfterInstanciation()

    #---------------------------------------------------------------#

    def onAfterInstanciation(self):
        """
            Handle Knowledge Engine specific actions after this object
            has been loaded into memory.

            This is useful for performing backwards compatibility
        """

        #perform default processing
        ToolbarTool.onAfterInstanciation(self)

    #---------------------------------------------------------------#

    def isPreviewPermitted(self):
        """
            Return if the Element is allowed to be previewed.

            By default all elements can't be previewed, some however
            should can be previewed. eg: HTMLHeaderFooters
        """

        return true

    #---------------------------------------------------------------#

    def getContent(self, contentZone, forGenericObject = None, assessment = None):
        """
            Return the Element generated
            content for the specified contentZone (a string).

            This method is called by the Model.index_html dtml file
            to customise the appearance of the output.

            By overriding this method, Elements have the opportunity
            to perform customization of the output from a Model
            during the assessment process.
        """


        #the result
        result = ""

        if contentZone == "PAGE_DECLARATIONS":

            #add the renderPageList method (always)
            result = self._v_javascriptPageList

        elif contentZone == "PAGE_REFRESH":

            #get the section we are currently in (the forGenericObject)
            lPage = forGenericObject

            #is there more than one section? (add calls to renderPageList)
            if lPage is not None and len(lPage.getModel().getPages(assessment)) > 1:
                result += 'renderPageList($("navTop"));'
                result += 'renderPageList($("navBottom"));'

        elif contentZone == "TOOLBAR_TOP" or contentZone == "TOOLBAR_BOTTOM":

            #output the button
            if contentZone == "TOOLBAR_TOP":
                prefix = "Top"
            else:
                prefix = "Bottom"

            #get the section we are currently in (the forGenericObject)
            lPage = forGenericObject

            #output the sections (if we have been supplied a context page)
            if lPage is not None:
                #get the model for the page
                lModel = lPage.getModel()

                #get the pages from the model
                lPages = lModel.getPages(assessment)

                #is there more than one page?
                if len(lPages) > 1:
                    #output the section list
                    result += '<select class="keToolbarDropDown" name="nav%s" id="nav%s" onChange="navigateToPage(getPage(getSelectValue(this)));">' % (prefix, prefix)

                    #output the current section
                    #(the rest may be hidden and will be rendered dynamically)
                    result += '<option id="%s" value="%s" selected>%s</option>' % (lPage.getIdentity(), lPage.getIdentity(), toHTML(lPage.getNavigationTitle()))

                    #output the end of the list
                    result += '</select>'

                else:
                    #only one section
                    result += '<span class="keDropDown" name="nav%s" id="nav%s">%s</span>' % (prefix, prefix, toHTML(lPage.getNavigationTitle()))

            else:
                #output preview style
                result += '<select class="keDropDown">'
                result += '<option>Preview</option>'
                result += '</select>'

        return result

    #---------------------------------------------------------------#

    ## The Javascript to dynamically update the model section list

    _v_javascriptPageList = """
    function renderPageList(cmbPageList) {
        if (cmbPageList != null) {
            var optionIdx = 0;
            for(var i = 0; i < arrPages.length; i++) {
                var section = arrPages[i];
                if (section.isShown()) {
                    if (optionIdx < cmbPageList.options.length && cmbPageList.options.item(optionIdx).value == section.getIdentity()) {
                        optionIdx++;
                    } else {
                        //var optPage = document.createElement("option");
                        
                        //optPage.text = section.getTitle();
                        //optPage.value = section.getIdentity();

                        var optPage = new Option( section.getTitle(), section.getIdentity() )

                        //add to the end?
                        if (optionIdx == cmbPageList.options.length) {
                            //cmbPageList.appendChild(optPage);
                            cmbPageList.options.add(optPage);
                        } else {
                            cmbPageList.options.add(optPage, optionIdx);
                        } //if
                        optionIdx++;
                    } //if
                } else {
                    if (optionIdx < cmbPageList.options.length && cmbPageList.options.item(optionIdx).value == section.getIdentity()) {
                        //cmbPageList.options.remove(optionIdx);
                        cmbPageList.options[ optionIdx ] = null;

                    } else {
                        //skip:everything is ok for this section
                    } //if
                } //if
            } //for
        } //if
    } //renderPageList
    """

    #---------------------------------------------------------------#


#####################################################################
## Class Initialisation

# Register Class Information with the Knowledge Engine
registerGenericObjectClass(PageList)

#####################################################################
